package com.wufun.overseas.main.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fasterxml.jackson.databind.JavaType;
import com.wufun.baselibrary.base.BaseApplication;
import com.wufun.baselibrary.download.CommonDownloadFactory;
import com.wufun.baselibrary.download.CommonDownloadTask;
import com.wufun.baselibrary.impl.AdapterInterface;
import com.wufun.baselibrary.net.HttpUtils;
import com.wufun.baselibrary.utils.DensityUtil;
import com.wufun.baselibrary.utils.LogUtils;

import com.wufun.overseas.R;
import com.wufun.overseas.adapters.MyHomerAdapter;
import com.wufun.overseas.adapters.TitlePopoAdapter;
import com.wufun.overseas.main.activity.DownloadManagerActivity;
import com.wufun.overseas.main.activity.SearchDetailActcivity;
import com.wufun.overseas.main.activity.SetWebViewActivity;
import com.wufun.overseas.main.base.MyApplication;
import com.wufun.overseas.main.base.MyFragment;
import com.wufun.overseas.models.bean.MyHomeBean;
import com.wufun.overseas.models.bean.SelectTypeBean;
import com.wufun.overseas.models.bean.TitlePopoWinBean;
import com.wufun.overseas.models.db.DownLoadModel;
import com.wufun.overseas.rpc.RpcConstant;
import com.wufun.overseas.tools.DownloadManager;
import com.wufun.overseas.utils.JsonMapper;
import com.wufun.overseas.utils.PostNetDotUtil;
import com.wufun.overseas.view.IXListViewLoadMore;
import com.wufun.overseas.view.IXListViewRefreshListener;
import com.wufun.overseas.view.XListView2;
import com.wufun.overseas.view.ptr.PtrClassicFrameLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by tangbl on 2017/11/30 0030.
 */

public class HomeFragment extends MyFragment implements AdapterInterface, CommonDownloadFactory.DownloadListener {

    @Bind(R.id.main_listview)
    XListView2 mainListview;
    @Bind(R.id.mPtrFrame)
    PtrClassicFrameLayout mPtrFrame;
    @Bind(R.id.bar_back_ll)
    LinearLayout barBackLl;
    @Bind(R.id.bar_title_tx)
    TextView barTitleTx;
    @Bind(R.id.tv_icon_down)
    ImageView iv_type;
    private PopupWindow mPopWindow = null;
    @Bind(R.id.layout_search_ll)
    LinearLayout layout_search;
    @Bind(R.id.bar_title_rl)
    RelativeLayout bar_title_rl;


    MyHomerAdapter adapter;
    SelectTypeBean typebean;
    //popowin
    TitlePopoAdapter myTitleAdapter;
    List<TitlePopoWinBean.DataBean.ListBean> list;
    private boolean isLoading = false;
    private List<MyHomeBean.DataBean.ListBean> datas = null;
    private int prfIndex = 0;
    private int position;
    protected CommonDownloadFactory factory;
    private boolean isFirstpage = false;
    String TitleName;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container
            , @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, null);
        ButterKnife.bind(this, view);
        return view;
    }

    private void initList() {
        adapter = new MyHomerAdapter(getContext(), this);
        datas = adapter.getData();
        mainListview.setAdapter(adapter);
        mainListview.setPullRefreshEnable(new IXListViewRefreshListener() {
            @Override
            public void onRefresh() {
                if (isLoading)
                    return;
                page = 1;
                prfIndex = 0;
                isFirstpage = true;
                getNetData();
            }
        });
        mainListview.setPullLoadEnable(new IXListViewLoadMore() {
            @Override
            public void onLoadMore() {
                if (isLoading)
                    return;
                getNetData();
            }
        });

        mainListview.setPreLoadCount(3);

    }

    public CommonDownloadFactory getFactory() {
        return factory;
    }

    public void showpopoWindon() {
        View contentView = LayoutInflater.from(getContext()).inflate(R.layout.popowindow_item, null);


        myTitleAdapter = new TitlePopoAdapter(getContext(), list);
        int width = DensityUtil.dp2px(getActivity(), 150);
        mPopWindow = new PopupWindow(contentView, width, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        final ListView list_item = contentView.findViewById(R.id.list_popo);
        list_item.setAdapter(myTitleAdapter);
        // 设置PopupWindow的背景
        mPopWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        //是在mPopWindow外 接收焦点 则mPopWindow dismis
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.setFocusable(true);
        int xoff = (getmWidth() - DensityUtil.dp2px(getActivity(), 96) - width) / 2;
        int yoff = DensityUtil.dp2px(getActivity(), 10);
        mPopWindow.showAsDropDown(bar_title_rl, xoff, -yoff);

        list_item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), SetWebViewActivity.class);
                intent.putExtra("url", list.get(position).getLink());
                getActivity().startActivity(intent);
                mPopWindow.dismiss();
                PostNetDotUtil.PostTitleNetDot(getActivity(), list.get(position).getName(), TitleName);
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void initWidget(View... v) {
        super.initWidget(v);
        barBackLl.setVisibility(View.INVISIBLE);
        TitleName = getResources().getString(R.string.Home_Title);
        barTitleTx.setText(TitleName);
        iv_type.setVisibility(View.VISIBLE);

        factory = CommonDownloadFactory.get();
        factory.setListener(this);
        layout_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getContext().startActivity(new Intent(getContext(), SearchDetailActcivity.class));
            }
        });
        bar_title_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showpopoWindon();
            }
        });
        getSelectType();
        initList();
        getNetData();

        if (BaseApplication.getBaseApplication().isApkDebugable())
            showToast(MyApplication.getMyApplication().getDbName());

    }

    //获取popowin的接口
    public void getSelectType() {
        HttpUtils.doGet(RpcConstant.forumRootUrl + "/forum/welcome/getForumInfo", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                TitlePopoWinBean tb;
                list = new ArrayList<>();
                String str = response.body().string();
                if (str != null) {
                    JavaType javaType = JsonMapper.getInstance().createCollectionType(TitlePopoWinBean.class);
                    tb = JsonMapper.getInstance().fromJson(str, javaType);
                    if (tb != null && tb.getData().getList().size() > 0) {
                        for (int i = 0; i < tb.getData().getList().size(); i++) {
                            if (tb.getData().getList().get(i).getName().replaceAll(" ", "")
                                    .indexOf(TitleName.replaceAll(" ", "")) == -1) {
                                list.add(tb.getData().getList().get(i));
                            }
                        }
                    }
                }
            }
        });

    }

    private int page = 1;
    private MyHomeBean myHomeBean;

    public void getNetData() {
        isLoading = true;
        HttpUtils.doGet(RpcConstant.forumRootUrl + "/forum/welcome/getIndexList?uid=1&group_id=1&token=123&page=" + (page++) + "&limit=10&sign="+getResources().getString(R.string.app_flag), new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                LogUtils.e("tbl1:" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                String str1 = response.body().string();

                try {
                    JavaType javaType = JsonMapper.getInstance().createCollectionType(MyHomeBean.class);
                    myHomeBean = JsonMapper.getInstance().fromJson(response.body().string(), javaType);
                    if (myHomeBean != null && myHomeBean.getData().getList().size() > 0) {
                        if (myHomeBean.getData().getList().size() < 10) {
                            Message msg = new Message();
                            msg.what = 2;
                            cwjHandler.sendMessage(msg);
                        }
//                        if (isFirstpage) {
//                            datas.clear();
//                            isFirstpage = false;
//                        }

                        LogUtils.e("tbl:" + datas.size());
                        Message msg = new Message();
                        msg.what = 1;
                        cwjHandler.sendMessage(msg);
                    } else {
                        Message msg = new Message();
                        msg.what = 2;
                        cwjHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    LogUtils.e("tbl2:" + e.getMessage());
                    Message msg = new Message();
                    msg.what = 3;
                    cwjHandler.sendMessage(msg);
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @SuppressLint("HandlerLeak")
    Handler cwjHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1://成功 高速UI线程可以更新结果了
                    updateUI();
                    break;
                case 2://没有返回数据
                    mainListview.setNoMore();
                    break;
                case 3:
                    showToast(getResources().getString(R.string.getnetdata_error));
                    break;
                case 4:
                    adapter.setReflash();
                    break;
            }
            stopLoad();
        }
    };

    private void stopLoad() {
        mainListview.stopLoadMore();
        mainListview.stopRefresh();
        isLoading = false;
    }

    private void    updateUI() {
        if (isFirstpage) {
            datas.clear();
            isFirstpage = false;
        }
        if (adapter == null) {
            adapter = new MyHomerAdapter(getContext(), this);
            mainListview.setAdapter(adapter);
            datas = adapter.getData();
        }
        datas.addAll(myHomeBean.getData().getList());
        adapter.notifyDataSetChanged();
        if (prfIndex == datas.size() && datas.size() != 0) {
            mainListview.setNoMore();
            return;
        }
        prfIndex = datas.size();

    }


    @Override
    public void onAdapterItemClick(View view, int positions) {
        position = positions;

        MyHomeBean.DataBean.ListBean temp = null;
        try {
            temp = adapter.getItem(positions);
            Log.e("TAG", temp.getRelation_game().getGame_down_url_mote());
            if (temp.getRelation_game().getGame_down_url_mote() != null && temp.getRelation_game().getGame_down_url_mote().indexOf("apk") == -1) {
                DownLoadModel start = DownloadManager.getInstance().getDownloadByUrl(temp.getRelation_game().getGame_down_url_mote());
                if (start != null) {
                    if (start.getStatus() == CommonDownloadTask.STATUS_FINISH) {
                        StartGame(start.getDownloadUrl(), start.getGamePath() + "/" + start.getGameZipName().replace(".zip", ""));
                    } else if (start.getStatus()==CommonDownloadTask.STATUS_STOP){
                         // 继续下载
                        download(start);
                    }else if (start.getStatus()==CommonDownloadTask.STATUS_PROGRESS){
                        if (factory.isExitTask(start.getDownloadUrl()))
                            factory.cancelTask(start.getDownloadUrl());
                        else{
                            download(start);
                        }


                    }else{
                        download(start);
                    }
                } else {

                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < temp.getRelation_game().getGame_tag_info().size(); i++) {
                        if (i < (temp.getRelation_game().getGame_tag_info().size() - 1)) {
                            sb.append(temp.getRelation_game().getGame_tag_info().get(i).getId() + ",");
                        } else {
                            sb.append(temp.getRelation_game().getGame_tag_info().get(i).getId());
                        }
                    }
                    addDownloadToDB(temp.getRelation_game().getGame_name(),
                            temp.getRelation_game().getGame_down_url_mote(),
                            temp.getRelation_game().getGame_id(),
                            temp.getRelation_game().getGame_ico_remote(),
                            temp.getRelation_game().getGame_size(),
                            sb.toString());

                    Intent intent = new Intent(getActivity(), DownloadManagerActivity.class);
                    intent.putExtra("title", "Download Management");
                    getActivity().startActivity(intent);
                }
            } else {
                Toast.makeText(getContext(), "URI ERROR", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(getContext(), "URI ERROR", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }


    }
    private void download(DownLoadModel start) {
        try {
            factory.addTask(new CommonDownloadTask(start.getDownloadUrl()
                    , start.getGameZipName()
                    , start.getDownloadDir()
                    , start.getGameName()));
        } catch (Exception e) {
            showToast(e.getMessage());
        }
    }
    @Override
    public void onDownloadStart(String url, String gameName) {
        DownloadManager.getInstance().updataDownload(url, CommonDownloadTask.STATUS_START);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }

    @Override
    public void onDownloadWait(String url, long size) {

    }


    @Override
    public void onDownloadProgress(String url, int progress, String speed) {
        DownloadManager.getInstance().updataDownload(url, CommonDownloadTask.STATUS_PROGRESS);
        adapter.getSpeed(progress,speed);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);


    }

    @Override
    public void onDownloadFinish(String url, String gameName) {
        DownloadManager.getInstance().updataDownload(url, CommonDownloadTask.STATUS_FINISH);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }

    @Override
    public void onDownloadError(String url, String gameName) {
        DownloadManager.getInstance().updataDownload(url, CommonDownloadTask.STATUS_ERROR);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }

    @Override
    public void onDownloadStarZIP(String url, String gameName) {
        DownloadManager.getInstance().updataDownload(url, CommonDownloadTask.STATUS_STSRT_ZIP);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }

    @Override
    public void onDownloadZIPProgress(String url, int progress, String speed) {
        DownloadManager.getInstance().updataDownload(url, CommonDownloadTask.STATUS_ZIP_PROGRESS);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }

    @Override
    public void onDownloadZIPError(String url, String gameName) {
        DownloadManager.getInstance().updataDownload(url, CommonDownloadTask.STATUS_ZIP_FAIL);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }


    @Override
    public void onDownloadStop(String url, String gameName) {
        DownloadManager.getInstance().updataDownload(url, CommonDownloadTask.STATUS_STOP);
        Log.e("TAG", "onDownloadStop");
        datas.get(position).setGame_state(CommonDownloadTask.STATUS_STOP);
        Message msg = new Message();
        msg.what = 4;
        cwjHandler.sendMessage(msg);
    }


}
